{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2020 The TensorFlow Authors.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "# TensorFlow Addons Losses: TripletSemiHardLoss\n",
        "\n",
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/addons/tutorials/losses_triplet\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/addons/blob/master/docs/tutorials/losses_triplet.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/addons/blob/master/docs/tutorials/losses_triplet.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/addons/docs/tutorials/losses_triplet.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xHxb-dlhMIzW"
      },
      "source": [
        "## Overview\n",
        "This notebook will demonstrate how to use the TripletSemiHardLoss function in TensorFlow Addons.\n",
        "\n",
        "### Resources:\n",
        "* [FaceNet:  A Unified Embedding for Face Recognition and Clustering](https://arxiv.org/pdf/1503.03832.pdf)\n",
        "* [Oliver Moindrot's blog does an excellent job of describing the algorithm in detail](https://omoindrot.github.io/triplet-loss)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bQwBbFVAyHJ_"
      },
      "source": [
        "## TripletLoss\n",
        "\n",
        "As first introduced in the FaceNet paper, TripletLoss is a loss function that trains a neural network to closely embed features of the same class while maximizing the distance between embeddings of different classes.  To do this an anchor  is chosen along with one negative and one positive sample.\n",
        "![fig3](https://user-images.githubusercontent.com/18154355/61485418-1cbb1f00-a96f-11e9-8de8-3c46eef5a7dc.png)\n",
        "\n",
        "**The loss function is described as a Euclidean distance function:**\n",
        "\n",
        "![function](https://user-images.githubusercontent.com/18154355/61484709-7589b800-a96d-11e9-9c3c-e880514af4b7.png)\n",
        "\n",
        "Where A is our anchor input,  P is the positive sample input,  N is the negative sample input, and alpha is some margin you use to specify when a triplet has become too \"easy\" and you no longer want to adjust the weights from it."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wPJ5521HZHeL"
      },
      "source": [
        "## SemiHard Online Learning\n",
        "As shown in the paper, the best results are from triplets known as \"Semi-Hard\". These are defined as triplets where the negative is farther from the anchor than the positive, but still produces a positive loss. To efficiently find these triplets you utilize online learning and only train from the Semi-Hard examples in each batch. \n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MUXex9ctTuDB"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6Vyo25M2ba1P"
      },
      "outputs": [],
      "source": [
        "!pip install -U tensorflow-addons"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IqR2PQG4ZaZ0"
      },
      "outputs": [],
      "source": [
        "import io\n",
        "import numpy as np"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WH_7-ZYZYblV"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "import tensorflow_addons as tfa\n",
        "import tensorflow_datasets as tfds"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0_D7CZqkv_Hj"
      },
      "source": [
        "## Prepare the Data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iXvByj6wcT7d"
      },
      "outputs": [],
      "source": [
        "def _normalize_img(img, label):\n",
        "    img = tf.cast(img, tf.float32) / 255.\n",
        "    return (img, label)\n",
        "\n",
        "train_dataset, test_dataset = tfds.load(name=\"mnist\", split=['train', 'test'], as_supervised=True)\n",
        "\n",
        "# Build your input pipelines\n",
        "train_dataset = train_dataset.shuffle(1024).batch(32)\n",
        "train_dataset = train_dataset.map(_normalize_img)\n",
        "\n",
        "test_dataset = test_dataset.batch(32)\n",
        "test_dataset = test_dataset.map(_normalize_img)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KR01t9v_fxbT"
      },
      "source": [
        "## Build the Model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wvOPPuIKhLJi"
      },
      "source": [
        "![fig2](https://user-images.githubusercontent.com/18154355/61485417-1cbb1f00-a96f-11e9-8d6a-94964ce8c4db.png)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "djpoAvfWNyL5"
      },
      "outputs": [],
      "source": [
        "model = tf.keras.Sequential([\n",
        "    tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1)),\n",
        "    tf.keras.layers.MaxPooling2D(pool_size=2),\n",
        "    tf.keras.layers.Dropout(0.3),\n",
        "    tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'),\n",
        "    tf.keras.layers.MaxPooling2D(pool_size=2),\n",
        "    tf.keras.layers.Dropout(0.3),\n",
        "    tf.keras.layers.Flatten(),\n",
        "    tf.keras.layers.Dense(256, activation=None), # No activation on final dense layer\n",
        "    tf.keras.layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1)) # L2 normalize embeddings\n",
        "\n",
        "])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HYE-BxhOzFQp"
      },
      "source": [
        "## Train and Evaluate"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NxfYhtiSzHf-"
      },
      "outputs": [],
      "source": [
        "# Compile the model\n",
        "model.compile(\n",
        "    optimizer=tf.keras.optimizers.Adam(0.001),\n",
        "    loss=tfa.losses.TripletSemiHardLoss())\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TGBYNGxgVDrj"
      },
      "outputs": [],
      "source": [
        "# Train the network\n",
        "history = model.fit(\n",
        "    train_dataset,\n",
        "    epochs=5)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1Y--0tK69SXf"
      },
      "outputs": [],
      "source": [
        "# Evaluate the network\n",
        "results = model.predict(test_dataset)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dqSuLdVZGNrZ"
      },
      "outputs": [],
      "source": [
        "# Save test embeddings for visualization in projector\n",
        "np.savetxt(\"vecs.tsv\", results, delimiter='\\t')\n",
        "\n",
        "out_m = io.open('meta.tsv', 'w', encoding='utf-8')\n",
        "for img, labels in tfds.as_numpy(test_dataset):\n",
        "    [out_m.write(str(x) + \"\\n\") for x in labels]\n",
        "out_m.close()\n",
        "\n",
        "\n",
        "try:\n",
        "  from google.colab import files\n",
        "  files.download('vecs.tsv')\n",
        "  files.download('meta.tsv')\n",
        "except:\n",
        "  pass"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VAtj_m6Z_Uwe"
      },
      "source": [
        "## Embedding Projector"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y4rjlG9rlbVA"
      },
      "source": [
        "The vector and metadata files can be loaded and visualized here: https://projector.tensorflow.org/\n",
        "\n",
        "You can see the results of our embedded test data when visualized with UMAP:\n",
        "![embedding](https://user-images.githubusercontent.com/18154355/61600295-e6470380-abfd-11e9-8a00-2b25e7e6916f.png)\n"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "losses_triplet.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
